//
//  PeopleNearViewController.m
//  HotWord
//
//  Created by Ji Qi on 12-6-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "QAWallViewController.h"
#import "SliderBtn.h"
#import "WallListCell.h"
#import "QAWallDetailViewController.h"
#import "QAWallAddQuestionViewController.h"
#import "Question.h"
#import "QuestionAnswer.h"

@interface QAWallViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
{
    BOOL    _loadingMore;
    BOOL    _noMore;
    
    BOOL    _haveLoaded;
    NSMutableArray *_questions;
}

@property (retain, nonatomic) IBOutlet UITableView *wallTableView;
@property (retain, nonatomic) IBOutlet UIView *addQuestionView;
@property (retain, nonatomic) IBOutlet UIImageView *fadeImageView;
@property (retain, nonatomic) IBOutlet UIImageView *nullDataImageView;
@property (retain, nonatomic) IBOutlet UIButton *refreshBtn;
@property (retain, nonatomic) IBOutlet UIImageView *qaMarkImageView;

@end

@implementation QAWallViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)dealloc {
    [_wallTableView release];
    [_addQuestionView release];
    [_questions release];
    [_fadeImageView release];
    [_nullDataImageView release];
    [_refreshBtn release];
    [_qaMarkImageView release];
    [super dealloc];
}


- (void)viewDidUnload
{
    [self setWallTableView:nil];
    [self setAddQuestionView:nil];
    [self setFadeImageView:nil];
    [self setNullDataImageView:nil];
    [self setRefreshBtn:nil];
    [self setQaMarkImageView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.wallTableView.top = self.view.height;
    _noMore = YES;
    SliderBtn *sliderBtn = (SliderBtn *)[[[NSBundle mainBundle] loadNibNamed:@"SliderBtn" owner:self options:nil] objectAtIndex:0];
    sliderBtn.tag = 111;
    [self.view addSubview:sliderBtn];
    
    if (_isMyQa)
    {
        _qaMarkImageView.image = ImageNamed(@"myqa_lable.png");
    }
    _questions = [[NSMutableArray alloc] init];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_isNeedRefresh)
    {
        _isNeedRefresh = NO;
        [self request];
    }
    
    if (![APP_DELEGATE.touchMaskView isDescendantOfView:self.view])
    {
        [self.view insertSubview:APP_DELEGATE.touchMaskView belowSubview:[self.view viewWithTag:111]];
    }

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!_haveLoaded) {
        _haveLoaded = YES;
        [self request];
    }
}

- (void)request
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"memberId"];
    }
    [params setObject:@"1" forKey:@"pageNo"];
    [params setObject:@"10" forKey:@"pageSize"];
    HotWordRequestType type = HotWordRequestTypeGetQuestion;
    if (_isMyQa)
    {
        type = HotWordRequestTypeGetUserQuestion;
    }
    [[ServiceHelper sharedService] requestServerForMethod:type WithParameters:params AndCallBackScope:self AndSuccessSel:@"getQuestionSuccess:" AndFailedSel:@"getQuestionFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Loading..."];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[HTActivityIndicator currentIndicator] hide];
    [super viewWillDisappear:animated];
}

#pragma mark - IBAction
- (IBAction)tapOnAddQuestBtn:(id)sender
{
    QAWallAddQuestionViewController *addQuestionViewController = [[QAWallAddQuestionViewController alloc] init];
    [self.navigationController pushViewController:addQuestionViewController animated:YES];
    [addQuestionViewController release];
}

- (IBAction)tapOnRefreshBtn:(id)sender {
    [self request];
}
- (IBAction)tapOnSwitchBtn:(id)sender {
    
    
    QAWallViewController *wallViewController = [[[QAWallViewController alloc] init] autorelease];
    wallViewController.isMyQa = !_isMyQa;
    
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    
    [self.navigationController popToRootViewControllerAnimated:NO];
    UINavigationController *navController = (UINavigationController *)APP_DELEGATE.window.rootViewController;
    [navController pushViewController:wallViewController animated:NO];
    
    [UIView commitAnimations];

}


#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == [_questions count]){// && !_noMore) {
        UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
        
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (_loadingMore) {
            UIActivityIndicatorView	*activiter = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
            activiter.center = cell.center;
            activiter.left = 100;
            [activiter startAnimating];
            [cell addSubview:activiter];
            cell.textLabel.text = @"Loading...";
        }
        else
        {
            cell.textLabel.text = @"MORE";
        }
        return cell;
    }
    else {
        
        static NSString *CellIdentifier = @"WallListCell";
        
        WallListCell *cell = (WallListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"WallListCell" owner:self options:nil] objectAtIndex:0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        Question *question = [_questions objectAtIndex:indexPath.row];
        [cell setDataSourceWithQuestion:question];
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == [_questions count]) {
        return 40;
    }
    return 160;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_noMore || [_questions count] == 0) {
        return [_questions count];
    }
    return [_questions count] + 1;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [_questions count]) {
        [self loadMore];
    }
    else {
        Question *question = [_questions objectAtIndex:indexPath.row];
        QAWallDetailViewController *wallDetailViewController = [[QAWallDetailViewController alloc] initwithQuestion:question];
        [self.navigationController pushViewController:wallDetailViewController animated:YES];
        [wallDetailViewController release];
    }
}

#pragma mark - UIScrollViewDelegate
//
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    [UIView animateWithDuration:0.4 animations:^{
//        if (scrollView.contentOffset.y > 10)
//        {
//            _fadeImageView.alpha = 1;
//        }
//        else
//        {
//            _fadeImageView.alpha = 0;
//        }
//    }];
//}

//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    [UIView animateWithDuration:0.6 animations:^{
//        _fadeImageView.alpha = 0;
//    }];
//}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
	if (_loadingMore || _noMore) {
		return;
	}
	CGPoint origin = scrollView.bounds.origin;
	if (scrollView.contentSize.height - origin.y <= self.view.bounds.size.height - 40) {
		[self loadMore];
	}
    
//    if (!decelerate)
//    {
//        [UIView animateWithDuration:0.6 animations:^{
//            _fadeImageView.alpha = 0;
//        }];
//    }
}

- (void)loadMore
{
    _loadingMore = YES;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"memberId"];
    }
    [params setObject:[NSString stringWithFormat:@"%d", [_questions count]/10 + 1] forKey:@"pageNo"];
    [params setObject:@"10" forKey:@"pageSize"];
    
    HotWordRequestType type = HotWordRequestTypeGetQuestion;
    if (_isMyQa)
    {
        type = HotWordRequestTypeGetUserQuestion;
    }

    [[ServiceHelper sharedService] requestServerForMethod:type WithParameters:params AndCallBackScope:self AndSuccessSel:@"getQuestionSuccess:" AndFailedSel:@"getQuestionFailed:"];
    [self.wallTableView reloadData];
}

- (void)getQuestionSuccess:(NSObject *)result
{
    if (![result isKindOfClass:[NSDictionary class]]) {
        [self requestHandle];
        return;
    }
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        if (!_loadingMore)
        {
            [_questions removeAllObjects];
        }
        
        NSArray *questionDics = [dic objectForKey:@"data"];
        for (NSDictionary *questionDic in questionDics) {
            Question *question = [[[Question alloc] init] autorelease];
            question.memberId = [UtilHelper getStringValue:[questionDic objectForKey:@"member_id"]];
            question.avater = [UtilHelper getStringValue:[questionDic objectForKey:@"avater"]];
            question.nickName = [UtilHelper getStringValue:[questionDic objectForKey:@"nick"]];
            question.title = [UtilHelper getStringValue:[questionDic objectForKey:@"title"]];
            question.content = [UtilHelper getStringValue:[questionDic objectForKey:@"content"]];
            question.examTag = [UtilHelper getStringValue:[questionDic objectForKey:@"examTag"]];
            question.timestamp = [UtilHelper getStringValue:[questionDic objectForKey:@"timestamp"]];
            question.isAnonymous = [UtilHelper getStringValue:[questionDic objectForKey:@"isanonymous"]];
            
            NSArray *answerDics = [questionDic objectForKey:@"answers"];
            NSMutableArray *answers = [NSMutableArray array];
            for (NSDictionary *answerDic in answerDics)
            {
                QuestionAnswer *answer = [[QuestionAnswer alloc] init];
                answer.nickName = [UtilHelper getStringValue:[answerDic objectForKey:@"nickname"]];
                answer.avater = [UtilHelper getStringValue:[answerDic objectForKey:@"avater"]];
                answer.introduce = [UtilHelper getStringValue:[answerDic objectForKey:@"introduce"]];
                answer.content = [UtilHelper getStringValue:[answerDic objectForKey:@"content"]];
                answer.timestamp = [UtilHelper getStringValue:[answerDic objectForKey:@"timestamp"]];

                [answers addObject:answer];
                [answer release];
            }
            
            question.answers = answers;
            
            NSArray *tagArray = [questionDic objectForKey:@"tags"];
            NSDictionary *tagDic = nil;
            if ([tagArray count] > 0)
            {
                tagDic = [tagArray objectAtIndex:0];
            }
            QuestionTag *tag = [[QuestionTag alloc] init];
            if (tagDic)
            {
                tag.tagId = [UtilHelper getStringValue:[tagDic objectForKey:@"tagid"]];
                tag.name = [UtilHelper getStringValue:[tagDic objectForKey:@"name"]];
                tag.superId = [UtilHelper getStringValue:[tagDic objectForKey:@"superid"]];
                tag.superName = [UtilHelper getStringValue:[tagDic objectForKey:@"supername"]];
            }
            
            question.tag = tag;
            [tag release];
            [_questions addObject:question];
        }
        
        if ([questionDics count] < 10) {
            _noMore = YES;
        }
        else {
            _noMore = NO;
        }
        [[HTActivityIndicator currentIndicator] hide];
    }
    else {
        if (!_loadingMore) {
            [[HTActivityIndicator currentIndicator] displayMessage:@"Loading Failed!"];
        }
    }
    
    [self requestHandle];

    _loadingMore = NO;
    [self.wallTableView reloadData];

}

- (void)requestHandle
{
    _nullDataImageView.hidden = YES;
    _refreshBtn.hidden = YES;
    if ([_questions count] == 0)
    {
        _nullDataImageView.hidden = NO;
        _refreshBtn.hidden = NO;
        
        if (_addQuestionView.alpha < 1)
        {
            [UIView animateWithDuration:0.4
                             animations:^{
                                 _addQuestionView.alpha = 1;
                             }];
        }
    }
    else
    {
        if (!_loadingMore)
        {
            [UIView animateWithDuration:0.5 animations:^{
                self.wallTableView.top = 0;
                
            } completion:^(BOOL finished) {
                if (_addQuestionView.alpha < 1)
                {
                    [UIView animateWithDuration:0.4
                                     animations:^{
                                         _addQuestionView.alpha = 1;
                                     }];
                }
                
            }];
        }
    }
}


- (void)getQuestionFailed:(NSObject *)result
{
    if (!_loadingMore) {
        
        [[HTActivityIndicator currentIndicator] displayMessage:@"Loading Failed!"];
    }
    [self requestHandle];

    _loadingMore = NO;
    [self.wallTableView reloadData];
    
}

@end
